import { useState, useEffect } from 'react';

import { EditOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { Layout, Typography, Button, Modal, Input, List, Space, message, Form, Upload } from 'antd';
import axios from 'axios';
import * as XLSX from 'xlsx';
import FieldDictionary from './components/FieldDictionary';

import Navbar from './components/Navbar';

import './App.css';

const { Header, Content, Footer } = Layout;
const { Title } = Typography;

function App() {
  
  const [fields, setFields] = useState([]);
  const [editingField, setEditingField] = useState(null);
  const [tables, setTables] = useState([]);
  const [currentTable, setCurrentTable] = useState(null);
  const [isCreateTableModalVisible, setIsCreateTableModalVisible] = useState(false);
  const [newTableName, setNewTableName] = useState('');
  const [newTableEnglishName, setNewTableEnglishName] = useState('');
  const [searchTableText, setSearchTableText] = useState('');
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editingTable, setEditingTable] = useState(null);
  const [form] = Form.useForm();

  // 加载所有表
  const loadTables = async () => {
    try {
      const response = await axios.get('/api/tables');
      // 确保获取的数据是数组格式
      const tableData = Array.isArray(response.data) ? response.data : (response.data?.data || []);
      setTables(tableData);
    } catch (error) {
      console.error('加载表列表失败', error);
      message.error('加载表列表失败');
      return;
    }
  };

  useEffect(() => {
    loadTables();
  }, []);

  // 加载选中表的字段
  useEffect(() => {
    if (!currentTable) return;

const loadTableFields = async () => {
      try {
        const response = await axios.get(`/api/tables/${currentTable}/fields`);
        setFields(response.data);
      } catch (error) {
        console.error('加载字段数据失败', error);
        message.error('加载字段数据失败');
      }
    };

    loadTableFields();
  }, [currentTable]);

  // 编辑表名称
  const handleEditTable = async () => {
    try {
      const values = await form.validateFields();
      if (!values.editTableName.trim() || !values.editTableEnglishName.trim()) {
        message.warning('中文表名和英文表名不能为空');
        return;
      }

      await axios.put(`/api/tables/${editingTable.englishName}`, {
        newEnglishName: values.editTableEnglishName.trim(),
        newChineseName: values.editTableName.trim()
      });
      
      // 更新本地表列表
      setTables(tables.map(table => 
        table.englishName === editingTable.englishName
          ? { ...table, englishName: values.editTableEnglishName.trim(), chineseName: values.editTableName.trim() }
          : table
      ));
      
      // 如果正在编辑当前选中的表，更新当前选中表名
      if (currentTable === editingTable.englishName) {
        setCurrentTable(values.editTableEnglishName.trim());
      }
      
      setIsEditModalVisible(false);
      message.success('表名称更新成功');
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误，不显示错误消息
        return;
      }
      console.error('更新表名称失败', error);
      message.error(error.response?.data?.error || '更新表名称失败');
    }
  }

  // 显示编辑模态框
  const showEditModal = (table) => {
    setEditingTable(table);
    form.setFieldsValue({
      editTableName: table.chineseName,
      editTableEnglishName: table.englishName
    });
    setIsEditModalVisible(true);
  };

  // 创建新表
  const handleCreateTable = async () => {
    if (!newTableName.trim() || !newTableEnglishName.trim()) {
      message.warning('中文表名和英文表名不能为空');
      return;
    }

    try {
      await axios.post('/api/tables', {
        tableName: newTableEnglishName.trim(),
        chineseName: newTableName.trim()
      });
      setTables([...tables, {
        englishName: newTableEnglishName.trim(),
        chineseName: newTableName.trim()
      }]);
      setIsCreateTableModalVisible(false);
      setNewTableName('');
      setNewTableEnglishName('');
      message.success('表创建成功');
    } catch (error) {
      console.error('创建表失败', error);
      message.error(error.response?.data?.error || '创建表失败');
    }
  };

  // 删除表
  const handleDeleteTable = async (tableName) => {
    try {
      await axios.delete(`/api/tables/${tableName}`);
      setTables(tables.filter(name => name !== tableName));
      if (currentTable === tableName) {
        setCurrentTable(null);
        setFields([]);
      }
      message.success('表删除成功');
    } catch (error) {
      console.error('删除表失败', error);
      message.error('删除表失败');
    }
  };

  // 选择表
  const handleSelectTable = (tableName) => {
    setCurrentTable(tableName);
  };

  return (
    <Layout className="layout" style={{ minHeight: '100vh' }}>
      <Header className="header" style={{ position: 'fixed', zIndex: 1, width: '100%' }}>
        <Navbar  />
      </Header>
      <Content style={{ padding: '0 50px', marginTop: 64 }}>
        <div className="site-layout-content" style={{ background: '#fff', padding: 24, borderRadius: 8, boxShadow: '0 4px 20px rgba(0,0,0,0.08)', marginTop: 20 }}>
          <Title level={2} style={{ textAlign: 'center', marginBottom: 24 }}>数据字典管理</Title>
          
          <div style={{ display: 'flex', gap: 24 }}>
            {/* 表列表区域 */}
            <div style={{ width: '30%', minWidth: 250 }}>
              <div style={{ marginBottom: 16 }}>
                {/* 导入导出按钮 - 位于搜索框上方 */}
                <div style={{ marginBottom: '16px', textAlign: 'left' }}>
                  <Space>
                    <Upload
                      name="file"
                      beforeUpload={(file) => {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                          try {
                            const workbook = XLSX.read(e.target.result, { type: 'array' });
                            workbook.SheetNames.forEach(sheetName => {
                              const [chineseName, englishName] = sheetName.split('-');
                              if (!chineseName || !englishName) {
                                message.warning(`Sheet名称格式错误: ${sheetName}，应为"中文表名-英文表名"`);
                                return;
                              }
                              const worksheet = workbook.Sheets[sheetName];
                              const jsonData = XLSX.utils.sheet_to_json(worksheet);
                              fetch('/api/tables/import', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ chineseName, englishName, data: jsonData })
                              }).then(res => res.json()).then(() => {
                                message.success(`导入成功: ${chineseName}`);
                                loadTables();
                              }).catch(err => message.error(`导入失败: ${err.message}`));
                            });
                          } catch (err) { message.error('解析失败: ' + err.message); }
                        };
                        reader.readAsArrayBuffer(file);
                        return false;
                      }}
                      showUploadList={false}
                    >
                      <Button type="primary" icon={<UploadOutlined />}>导入Excel</Button>
                    </Upload>
                    <Button
                      icon={<DownloadOutlined />}
                      onClick={async () => {
                        try {
                          const res = await axios.get('/api/tables');
                          const workbook = XLSX.utils.book_new();
                          // 修改前
                          res.data.forEach(function(table) {
                            // ...
                          });
                          
                          // 修改后
                          // 使用let声明循环变量确保块级作用域
                          for (let i = 0; i < res.data.length; i++) {
                            const table = res.data[i];
                            const sheetName = table.chineseName + '-' + table.englishName;
                            
                            // 添加错误处理并使用IIFE捕获当前table值
                            (function(sheetName, table) {
                              axios.get('/api/tables/' + table.englishName + '/fields')
                                .then(function(fieldRes) {
                                  const data = fieldRes.data.map(function(f) {
                                    return {'英文字段': f['englishField'], '中文字段': f['chineseName']};
                                  });
                                  const worksheet = XLSX.utils.json_to_sheet(data);
                                  XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
                                  
                                  // 检查是否所有工作表都已添加
                                  if (Object.keys(workbook.Sheets).length === res.data.length) {
                                    XLSX.writeFile(workbook, '数据字典导出.xlsx');
                                    message.success('所有表导出完成');
                                  }
                                })
                                .catch(function(err) {
                                  message.error('获取' + sheetName + '字段失败: ' + err.message);
                                  console.error('API请求错误:', err);
                                });
                            })(sheetName, table);
                          }
                          
                          // 处理空数据情况
                          if (res.data.length === 0) {
                            message.warning('没有可导出的表数据');
                            XLSX.writeFile(workbook, '数据字典导出.xlsx');
                          }
                        } catch (err) { message.error('导出失败: ' + err.message); }
                      }}
                    >
                      导出Excel
                    </Button>
                  </Space>
                </div>

                {/* 搜索框 */}
                <Input
                  placeholder="搜索表名..."
                  value={searchTableText}
                  onChange={(e) => setSearchTableText(e.target.value)}
                  style={{ width: 200, marginBottom: 16 }}
                />

                {/* 数据表列表标题和新建按钮 */}
                <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Title level={4} style={{ margin: 0 }}>数据表列表</Title>
                  <Button type="primary" onClick={() => setIsCreateTableModalVisible(true)}>
                    + 新建表
                  </Button>
                </div>
              </div>
              
              <List
                dataSource={tables.filter(table => 
                  ((table?.chineseName || '').toLowerCase().includes((searchTableText || '').toLowerCase()) ||
  (table?.englishName || '').toLowerCase().includes((searchTableText || '').toLowerCase()))
                )}
                renderItem={table => (
                  <List.Item
                    actions={[
                      <Button 
                        type={currentTable === table.englishName ? "primary" : "default"} 
                        size="small" 
                        onClick={() => handleSelectTable(table.englishName)}
                      >
                        {currentTable === table.englishName ? "已选择" : "选择"}
                      </Button>,
                      <Button 
                        size="small" 
                        icon={<EditOutlined />}
                        onClick={() => showEditModal(table)}
                      >
                        编辑
                      </Button>,
                      <Button 
                        danger 
                        size="small" 
                        onClick={() => handleDeleteTable(table.englishName)}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <List.Item.Meta title={table.chineseName} description={`英文表名: ${table.englishName}`} />
                  </List.Item>
                )}
                locale={{ emptyText: '暂无数据表，请创建新表' }}
              />
            </div>
            
            {/* 字段管理区域 */}
            <div style={{ width: '70%' }}>
              {currentTable ? (
                <>
                  <Title level={4} style={{ marginBottom: 16 }}>
                    字段管理 - {tables.find(t => t.englishName === currentTable)?.chineseName || currentTable}
                  </Title>
                  <FieldDictionary 
                    fields={fields} 
                    onSaveFields={setFields} 
                    editingField={editingField} 
                    setEditingField={setEditingField} 
                    currentTable={currentTable} 
                  />
            
                </>
              ) : (
                <div style={{ textAlign: 'center', padding: 40, color: '#666' }}>
                  请从左侧选择或创建一个数据表
                </div>
              )}
            </div>
          </div>
        </div>
        
        {/* 创建表模态框 */}
        <Modal
          title="创建新数据表"
          visible={isCreateTableModalVisible}
          onCancel={() => setIsCreateTableModalVisible(false)}
          footer={[
            <Button key="cancel" onClick={() => setIsCreateTableModalVisible(false)}>取消</Button>,
            <Button key="submit" type="primary" onClick={handleCreateTable}>创建</Button>,
          ]}
        >
          <Form layout="vertical" name="create_table_form">
            <Form.Item
              name="tableName"
              label="中文表名"
              rules={[{ required: true, message: '请输入中文表名' }]}
            >
              <Input
                placeholder="请输入中文表名"
                value={newTableName}
                onChange={(e) => setNewTableName(e.target.value)}
              />
            </Form.Item>
            <Form.Item
              name="englishName"
              label="英文表名"
              rules={[
                { required: true, message: '请输入英文表名' },
                { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '英文表名只能包含字母、数字和下划线，且以字母或下划线开头' }
              ]}
            >
              <Input
                placeholder="请输入英文表名（用于数据库）"
                value={newTableEnglishName}
                onChange={(e) => setNewTableEnglishName(e.target.value)}
              />
            </Form.Item>
          </Form>
        </Modal>

        {/* 编辑表名称模态框 */}
        <Modal
          title="编辑数据表名称"
          visible={isEditModalVisible}
          onCancel={() => setIsEditModalVisible(false)}
          footer={[
            <Button key="cancel" onClick={() => setIsEditModalVisible(false)}>取消</Button>,
            <Button key="submit" type="primary" onClick={handleEditTable}>保存</Button>
          ]}
        >
          <Form form={form} layout="vertical" name="edit_table_form">
            <Form.Item
              name="editTableName"
            label="中文表名"
            rules={[{ required: true, message: '请输入中文表名' }]}
            >
              <Input
                placeholder="请输入中文表名"

              />
            </Form.Item>
            <Form.Item
              name="editTableEnglishName"
            label="英文表名"
            rules={[{ required: true, message: '请输入英文表名' }]}
            >
              <Input
                placeholder="请输入英文表名"

              />
            </Form.Item>
          </Form>
        </Modal>
      </Content>
      <Footer style={{ textAlign: 'center' }}>
        数据字典网站 ©{new Date().getFullYear()} | 本地数据存储解决方案
      </Footer>
    </Layout>
  );
}

export default App;